package com.member.web.controller.shop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.SysBizGoods;
import com.member.shop.domain.SysBizPop;
import com.member.shop.domain.SysBizShopSpecs;
import com.member.shop.mapper.SysBizGoodsMapper;
import com.member.shop.service.ISysBizGoodsService;
import com.member.shop.service.ISysBizShopSpecsService;
import com.member.shop.vo.SpecsData;
import com.member.web.controller.common.IdList;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 【商品规格】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-12-29
 **/
@RestController
@RequestMapping("/shop/specs")
public class SysBizShopSpecsController extends BaseController {
    @Resource
    private ISysBizShopSpecsService sysBizShopSpecsService;

    private void setTenantId(SysBizShopSpecs sysBizShopSpecs) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizShopSpecs.setTenantId(tenantId);
        }
    }

    /**
     * 查询商品规格列表
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizShopSpecs sysBizShopSpecs) {
        startPage();
        // setTenantId(sysBizShopSpecs);
        List<SysBizShopSpecs> list = sysBizShopSpecsService.selectSysBizShopSpecsList(sysBizShopSpecs);
        return getDataTable(list);
//        LambdaQueryWrapper<SysBizShopSpecs> queryWrapper = new LambdaQueryWrapper<SysBizShopSpecs>();
//        queryWrapper.like(StringUtils.isNotEmpty(sysBizShopSpecs.getSpecsName()), SysBizShopSpecs::getSpecsName, sysBizShopSpecs.getSpecsName());
//        queryWrapper.eq(SysBizShopSpecs::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
//        queryWrapper.eq(SysBizShopSpecs::getParentId, sysBizShopSpecs.getParentId());
//        queryWrapper.orderByDesc(SysBizShopSpecs::getCreateTime);
    }


    @PreAuthorize("@ss.hasPermi('shop:specs:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(SysBizShopSpecs sysBizShopSpecs) {
        // setTenantId(sysBizShopSpecs);
        List<SysBizShopSpecs> list = sysBizShopSpecsService.selectSysBizShopSpecsList(sysBizShopSpecs);
        return getDataTable(list);
    }


    /**
     * 查询【父规格】下所有的【子规格】
     */
    @PreAuthorize("@ss.hasPermi('goods:specs:list')")
    @PostMapping("/selectSpecs")
    public List<SpecsData> selectSpecs(@RequestBody IdList ids) {

        List<SpecsData> result = new ArrayList<>();
        for (Long id : ids.getIds()) {
            //查询父规格
            SysBizShopSpecs sysBizGoodsSpecsParent = sysBizShopSpecsService.selectSysBizShopSpecsById(id);
            SysBizShopSpecs sysBizShopSpecsChild = new SysBizShopSpecs();

            SpecsData specsData = new SpecsData();
            specsData.setSpecsId(sysBizGoodsSpecsParent.getId());
            specsData.setSpecsName(sysBizGoodsSpecsParent.getSpecsName());
            //根据父规格id 查询子规格
            sysBizShopSpecsChild.setParentId(sysBizGoodsSpecsParent.getId());
            List<SysBizShopSpecs> goodsSpecsDataList = sysBizShopSpecsService.selectSysBizShopSpecsList(sysBizShopSpecsChild);

            ArrayList<SpecsData> childs = new ArrayList<SpecsData>();
            for (SysBizShopSpecs bizGoodsSpecsData : goodsSpecsDataList) {
                SpecsData childSpecsData = new SpecsData();
                childSpecsData.setSpecsId(bizGoodsSpecsData.getId());
                childSpecsData.setSpecsName(bizGoodsSpecsData.getSpecsName());
                childs.add(childSpecsData);
            }
            specsData.setChilds(childs);
            result.add(specsData);
        }
        return result;
    }

    /**
     * 导出商品规格列表
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:export')")
    @Log(title = "商品规格", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizShopSpecs sysBizShopSpecs) {
        setTenantId(sysBizShopSpecs);
        List<SysBizShopSpecs> list = sysBizShopSpecsService.selectSysBizShopSpecsList(sysBizShopSpecs);
        ExcelUtil<SysBizShopSpecs> util = new ExcelUtil<SysBizShopSpecs>(SysBizShopSpecs.class);
        util.exportExcel(response, list, "商品规格数据");
    }

    /**
     * 获取商品规格详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizShopSpecsService.selectSysBizShopSpecsById(id));
    }

    /**
     * 新增商品规格
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:add')")
    @Log(title = "商品规格", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizShopSpecs sysBizShopSpecs) {
        return toAjax(sysBizShopSpecsService.insertSysBizShopSpecs(sysBizShopSpecs));
    }

    /**
     * 修改商品规格
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:edit')")
    @Log(title = "商品规格", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizShopSpecs sysBizShopSpecs) {
        return toAjax(sysBizShopSpecsService.updateSysBizShopSpecs(sysBizShopSpecs));
    }

    @Resource
    private SysBizGoodsMapper sysBizGoodsMapper;

    /**
     * 删除商品规格
     */
    @PreAuthorize("@ss.hasPermi('shop:specs:remove')")
    @Log(title = "商品规格", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        if (sysBizShopSpecsService.hasChildById(id)) {
            return warn("存在子规格,不允许删除");
        }
        LambdaQueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        List<SysBizGoods> sysBizGoods = sysBizGoodsMapper.selectList(sysBizGoodsLambdaQueryWrapper);
        if (sysBizGoods != null) {
            for (SysBizGoods sysBizGood : sysBizGoods) {
                JSONArray jsonArray = new JSONArray(sysBizGood.getSpecsData());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JSONArray childs = jsonObject.getJSONArray("childs");
                    for (int j = 0; j < childs.length(); j++) {
                        JSONObject jsonObject2 = childs.getJSONObject(j);

                        Long specsId = jsonObject2.getLong("specsId");
                        System.out.println("specsId的值为：" + specsId);
                        if (id == specsId) {
                            return warn("存在商品使用此规格，不可删除");
                        }
                    }
                }
            }
        }
        return toAjax(sysBizShopSpecsService.deleteSysBizShopSpecsById(id));
    }
}
